package org.babygo.connect.handler.server.file;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import org.babygo.connect.NettyFileOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReceiveFileInHandler extends ChannelInboundHandlerAdapter{
	private Logger log = LoggerFactory.getLogger(ReceiveFileInHandler.class);

	private File f = null;

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//		if (file==null){
//			ByteBuf buf = (ByteBuf)msg;
//			int lineFeedIndex = buf.bytesBefore((byte)10);
//			byte[] protocol = new byte[lineFeedIndex-1];
//			buf.readBytes(protocol, 0, lineFeedIndex-1);
//			String fileName = new String(protocol);
//			file = NettyFileOperator.needToSavedFiles.get(fileName);
//			log.info("收到服务器传来的文件..." + fileName);
//			return;
//		}
		log.info("正在接受文件流...");
		if (f == null){
			File savefile = NettyFileOperator.OPERTATOR.saveFile();
			f = savefile;
		}
		ByteBuf m = (ByteBuf) msg;
		downLoadFile(f, m);
	}

	public void downLoadFile(File f, ByteBuf m){
		RandomAccessFile fileOutputStream = null;
		try {
			fileOutputStream = new RandomAccessFile(f,"rw");
			while(m.isReadable()){
				byte[] recevie = null;
				if (m.readableBytes()<1024){
					recevie = new byte[m.readableBytes()];
					m.readBytes(recevie, 0, m.readableBytes());
					log.info("下载即将结束!");
				} else {
					recevie = new byte[1024];
					m.readBytes(recevie, 0, 1024);
				}
				fileOutputStream.seek(fileOutputStream.length());
				fileOutputStream.write(recevie);
			}
		} catch (Exception e) {
			log.error("下载文件失败", e);
		} finally{
			log.info("下载文件成功");
			try {
				ReferenceCountUtil.release(m);
				fileOutputStream.close();
			} catch (IOException e) {
				log.error("关闭文件流错误", e);
			}
		}
	}
}